package com.theatre.userservice.Controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.theatre.userservice.Constant.JwtClaimsConstant;
import com.theatre.userservice.annotation.RequirePermission;
import com.theatre.userservice.Controller.contxet.BaseContext;
import com.theatre.userservice.exception.BusinessException;
import com.theatre.userservice.mapper.UserMapper;
import com.theatre.userservice.model.dto.PasswordDTO;
import com.theatre.userservice.model.dto.UserDTO;
import com.theatre.userservice.model.dto.UserLoginDTO;
import com.theatre.userservice.model.entity.User;
import com.theatre.userservice.model.vo.MenuVO;
import com.theatre.userservice.model.vo.Result;
import com.theatre.userservice.model.vo.UserLoginVO;
import com.theatre.userservice.model.vo.UserVO;
import com.theatre.userservice.model.vo.utils.FileUploadUtil;
import com.theatre.userservice.model.vo.utils.JwtUtil;
import com.theatre.userservice.properties.JwtProperties;
import com.theatre.userservice.service.MenuService;
import com.theatre.userservice.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户接口", description = "提供用户相关的接口")
@Slf4j
public class  UserController {

    @Autowired
    public UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    public UserService userService;
    @Autowired
    public MenuService MenuService;
    @Value("${upload.base-dir}")
    private String uploadBaseDir;
    @Value("${user.default-avatar}")
    private String defaultAvatar;


    @PostMapping("/guest-login")
    @Operation(summary = "游客注册登录")
    public Result<UserLoginVO> guestLogin() {
        // 1. 构造一个游客用户对象
        User guest = new User();
        guest.setUsername("guest_" + System.currentTimeMillis());
        guest.setRealName("游客" + System.currentTimeMillis());
        guest.setPassword(""); // 游客无密码
        guest.setRoleId(4L); // 游客角色
        guest.setAvatar(defaultAvatar);
        guest.setCreatedTime(LocalDateTime.now());
        guest.setUpdatedTime(LocalDateTime.now());
        // 2. 插入数据库（可选：也可以不插入，只是返回临时token）
        userMapper.insert(guest);
        //登录成功后，生成jwt令牌
        return getUserLoginVOResult(guest);
    }

    private Result<UserLoginVO> getUserLoginVOResult(User guest) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ID, guest.getId());
        claims.put(JwtClaimsConstant.ROLE_ID, guest.getRoleId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        List<MenuVO> menuList = MenuService.selectMenusByRoleId(guest.getRoleId());
        UserVO userVO = new UserVO();
        userVO.setId(guest.getId());
        userVO.setUsername(guest.getUsername());
        userVO.setRoleId(guest.getRoleId());
        userVO.setAvatar(guest.getAvatar());
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .userInfo(userVO)
                .menuList(menuList)
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }


    @PostMapping("/insert")
    @Operation(summary = "注册")
    public Result<String> insert(@RequestBody UserDTO userDto) {
        User user = new User();
        // 如果前端没有传头像，则设置默认头像
        if (StrUtil.isBlank(userDto.getAvatar())) {
            userDto.setAvatar(defaultAvatar);
        }
        BeanUtils.copyProperties(userDto, user);
        // 校验必填字段
        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名和密码不能为空");
        }
        // 对密码进行加密（例如MD5或BCrypt）
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        // 插入数据库
        userMapper.insert(user);
        return Result.success("注册成功");
    }
    @GetMapping("/get/{id}")
    @Operation(summary = "用户查询")
    public Result<User> get(@PathVariable("id") Long id) {
        User user = userMapper.selectById(id);
        return Result.success(user);
    }

    @PutMapping("/update")
    @Operation(summary = "用户更新")
    public Result<String> update(@RequestBody UserDTO userDto ) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userDto.getId());
        if (StrUtil.isBlank(userDto.getUsername())) {
            throw new BusinessException("用户名不能为空");
        } else {
            updateWrapper.set("username", userDto.getUsername());
        }

        if (StrUtil.isBlank(userDto.getRealName())) {
            throw new BusinessException("真实姓名不能为空");
        } else {
            updateWrapper.set("real_name", userDto.getRealName());
        }
        if (!StrUtil.isBlank(userDto.getPassword())) {
            updateWrapper.set("password", DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes(StandardCharsets.UTF_8)));
        }
        if (StrUtil.isBlank(userDto.getEmail())) {
            throw new BusinessException("邮箱不能为空");
        } else {
            updateWrapper.set("email", userDto.getEmail());
        }
        if (StrUtil.isBlank(userDto.getPhone())) {
            throw new BusinessException("手机号不能为空");
        } else {
            updateWrapper.set("phone", userDto.getPhone());
        }
        if (! (userDto.getRoleId() == null)) {
            updateWrapper.set("role_id", userDto.getRoleId());
        }
        userMapper.update(null, updateWrapper);
        return Result.success("用户更新成功");
    }

    @RequirePermission("user:manage")
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "用户删除")
    public Result<String> delete(@PathVariable("id") Long id) {
        userMapper.deleteById(id);
        return Result.success("用户删除成功");
    }

    @PutMapping("/editPassword")
    @Operation(summary = "修改密码")
    public Result<String> updatePassword(@RequestBody PasswordDTO passwordDTO) {
        log.info("修改密码{}",passwordDTO);
        try {
            userService.changePassword(passwordDTO);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            log.error("密码修改失败", e);
            return Result.error(e.getMessage());
        }
    }


    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("员工登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);
        return getUserLoginVOResult(user);
    }

    @PostMapping("/uploadAvatar")
    @Operation(summary = "上传用户头像")
    public Result<String> uploadAvatar(@RequestParam("avatar") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error("没有上传文件");
        }

        try {
            // 保存文件
            String relativePath = FileUploadUtil.saveFile(file, uploadBaseDir, "avatars");

            // 更新数据库对应用户头像
            User user = new User();
            user.setId(BaseContext.getUserId());
            user.setAvatar(relativePath);
            userMapper.updateById(user);

            return Result.success(relativePath);
        } catch (IOException e) {
            throw new BusinessException("上传头像失败");
        }
    }

    @RequirePermission("user:manage")
    @GetMapping("/getAll")
    @Operation(summary = "获取所有用户")
    public Result<List<User>> getAllUsers() {
        List<User> users = userMapper.selectList(null); // 查询所有用户
        List<User> userList = new ArrayList<>();
        // 将 User 转换为 UserVO
        for (User user : users) {
            User userone = new User();
            userone.setId(user.getId());
            userone.setUsername(user.getUsername());
            userone.setRoleId(user.getRoleId());
            userone.setRealName(user.getRealName());
            userone.setEmail(user.getEmail());
            userone.setPhone(user.getPhone());
            userone.setCreatedTime(user.getCreatedTime());
            userone.setUpdatedTime(user.getUpdatedTime());
            userList.add(userone);
        }
        return Result.success(userList);
    }

    @RequirePermission("user:manage")
    @DeleteMapping("/deleteBatch")
    @Operation(summary = "批量删除用户")
    public Result<String> deleteBatch(@RequestBody List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return Result.error("用户ID列表不能为空");
        }

        try {
            // 批量删除
            userMapper.deleteBatchIds(userIds);
            return Result.success("批量删除成功，共删除 " + userIds.size() + " 个用户");
        } catch (Exception e) {
            log.error("批量删除用户失败", e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }
}
